/**
 * This class represents a unit of a product
 * 
 * @author Konrad Paumann
 * @author Bernhard Denner
 * @author Maximilian Csuk
 * 
 */

import java.io.Serializable;


public class Unit implements Displayable, Serializable {
	private String name;
	private int factor;
	private Unit child = null;
	
	public Unit(String name, int factor) {
		this.name = name;
		this.factor = factor;
	}
	
	public Unit(String name, int factor, Unit child) {
		this.name = name;
		this.factor = factor;
		this.child = child;
	}
	
	public void setChild(Unit child) {
		this.child = child;
	}
	
	public Unit getChild() {
		return child;
	}
	
	public boolean hasChild() {
		return (child != null);
	}
	
	
	public void addUnit(String unitName, int unitFactor, String parentUnit) 
				throws ProductException {
		if (parentUnit == name) 
			child = new Unit(unitName, unitFactor, child);
		else {
			if (child == null)
				throw new ProductException("Elterneinheit " + parentUnit + " existiert nicht");

			child.addUnit(unitName, unitFactor, parentUnit);
		}
	}
	
	
	public Unit removeUnit(String unitName)
			throws ProductException {
		
		if (unitName == name) {
			return child;
		} else {
			if (child == null)
				throw new ProductException("Einheit " + unitName + " existiert nicht");
			
			child = child.removeUnit(unitName);
			return this;
		}
	}
	

	public int getFactor(String unitName) 
		throws ProductException {
		
		if (unitName == name)
			return factor;
		
		if (child == null)
			throw new ProductException("Einheit " + unitName + " existiert nicht");
		
		return factor * child.getFactor(unitName);
	}
	
	public String getDisplayString() {
		String msg = " ->" + factor + " " + name;
		if (child != null)
			return msg + child.getDisplayString();
		else
			return msg;
	}
	
}
